import React from 'react';
import {Table, Card, Divider} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {Link} from 'react-router-dom';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {conventEnumValueToString} from '../utils';
import {abandonData} from './api';
import {baseDataStatus} from '../Enum';
import {TABLE, PAGINATION_OPTIONS, FIXED_COLUMN_WIDTH, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT} from '../constants';

export class TablePanel extends React.PureComponent {
    constructor(props) {
        super(props);
        this.onChangeSort = this.onChangeSort.bind(this);
        this.state = {
            loading: false
        };
    }
    abandonConfirm = id => {
        this.setState({
            loading: true
        });
        const record = this.props.data.find(d => d.id === id);
        abandonData(id, record.rowVersion).then(res => {
            this.setState({
                loading: false
            });
            if(res.ok)
                this.props.onChangeSort();
        });
    }
    onChangeSort = (pagination, filters, sorter) => {
        this.props.onChangeSort({
            pageIndex: pagination.current - 1,
            pageSize: pagination.pageSize,
            sortedColumnKey: sorter.columnKey,
            sortedOrder: sorter.order,
        });
    };

    render() {
        const {formatMessage} = this.props.intl;
        const {pageIndex, pageSize, total} = this.props;
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            ...PAGINATION_OPTIONS
        };
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.brandName',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandName',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'brandName' && this.props.sortedOrder,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '货代编码'
            }),
            dataIndex: 'code',
            sorter: true,
            sortOrder: this.props.sortedColumnKey === 'code' && this.props.sortedOrder,
            render: (text, record) => <Link key="detail" to={routes.detail.format(record.id)}>{text}</Link>
        }, {
            title: formatMessage({
                id: 'tablePanel.column.name',
                defaultMessage: '货代名称'
            }),
            dataIndex: 'name',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.shortName',
                defaultMessage: '货代简称'
            }),
            dataIndex: 'shortName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(baseDataStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.operate',
                defaultMessage: '操作'
            }),
            dataIndex: 'operate',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, record) => {
                const updateOpt = hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(record.options, PERMISSION.update) &&
                    <Link key="update" to={routes.update.format(record.id)}>{
                        formatMessage({
                            id: 'tablePanel.operation.edit',
                            defaultMessage: '编辑'
                        })
                    }</Link>;
                const abandonOpt = hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(record.options, PERMISSION.abandon) &&
                    <WrappedPopconfirm
                        key="abandon"
                        placement="topLeft"
                        onConfirm={this.abandonConfirm}
                        id={record.id}
                        title={formatMessage({
                            id: 'tablePanel.message.abandon',
                            defaultMessage: '是否确认作废？'
                        })}>
                        <a>{formatMessage({
                            id: 'tablePanel.operation.abandon',
                            defaultMessage: '作废'
                        })}</a>
                    </WrappedPopconfirm>;
                return <span>{updateOpt}{updateOpt && abandonOpt && <Divider key="divider" type="vertical"/>}{abandonOpt}</span>;
            }
        }];
        return (
            <Card>
                <Table
                    className={'white-space-nowrap'}
                    columns={columns}
                    dataSource={this.props.data}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    pagination={pagination}
                    rowKey="id"
                    locale={locale}
                    {...TABLE}/>
            </Card>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
    sortedColumnKey: PropTypes.string,
    sortedOrder: PropTypes.string,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch} from './actions';
import {injectIntl} from './intl';

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    sortedColumnKey: state.getIn(['page', 'appState', 'queryBySort', 'sortedColumnKey']),
    sortedOrder: state.getIn(['page', 'appState', 'queryBySort', 'sortedOrder']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onChangeSort: option => dispatch(tableSearch(option)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));


